package com.zxp.mq.rocketmq.base.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

/**
 * 同步生产者
 * @author zxp
 * @date 2021/8/7 16:11
 */
@Slf4j
public class SyncProducer {

    public static void main(String[] args) throws Exception {
        //1、 实例化消息生产者Producer
        DefaultMQProducer mqProducer = new DefaultMQProducer("GP-syncProducer");

        //2、 设置NameServer的地址，注意broker-a.properties要暴露公网ip
        mqProducer.setNamesrvAddr("rocketmq-nameserver1:9876;rocketmq-nameserver2:9876");

        //3、启动Producer实例
        mqProducer.start();
        for (int i = 0; i < 10; i++) {
            // 4、创建消息，并指定Topic，Tag和消息体
            Message msg = new Message("topic1","tag1",("msg"+i).getBytes());

            // 5、发送消息到一个Broker
            SendResult result = mqProducer.send(msg);
            // 通过sendResult返回消息是否成功送达
            System.out.printf("%s%n", result);
            TimeUnit.SECONDS.sleep(1);
        }

        // 6、如果不再发送消息，关闭Producer实例。
        mqProducer.shutdown();
    }
}
